import os

from PyQt6.QtCore import QFile, QObject
from PyQt6.QtWidgets import QMessageBox


class FileServer(QObject):

    def __init__(self):
        super(FileServer, self).__init__()
        # 缓存字节数
        self.payloadsize = 64 * 1024

    def sendFile(self, filepath, sender, receiver):
        filepath = os.path.abspath(filepath)
        if os.path.exists(filepath):
            self.filesend = QFile(filepath)
            self.filesend.fileName()
            WebService.beginSendFile(self.filesend.fileName(), receiver, self.filesend.size())
            self.filemessage.emit(filepath, sender, receiver)
        else:
            QMessageBox.critical(None, '错误', '文件 %s 不存在' % filepath)
    #
    # def recvFile(self, filepath, size, peer):
    #     self.filerecv = QFile(filepath)
    #     self.filesize = size
    #     self.filesender = peer

    def handleFileSend(self):
        """
        通过 TCP 向客户端发送文件的具体方法
        """
        file = self.filesend
        self.filesend = None
        socket = WebService.tcpfileserver.nextPendingConnection()
        # 打开文件
        file.open(QFile.OpenModeFlag.ReadOnly)

        def write():
            """
            持续发送数据
            """
            while not file.atEnd():
                socket.write(file.read(self.payloadsize))
            self.filemessage()

        socket.bytesWritten.connect(write)

        # 发送数据
        block = file.read(self.payloadsize)
        socket.write(block)

        file.close()

    def handleFileRecv(self):
        """
        接收客户端通过 Tcp 发送文件的具体方法
        """
        filepath = self.filerecv
        filesize = self.filesize
        filesender = self.filepeer
        file = QFile(filepath)
        if file.exists():
            file.remove()
        file.open(QFile.OpenModeFlag.WriteOnly)
        while filesize > 0:
            block = WebService.tcpfilesocket.read(self.payloadsize)
            file.write(block)
            filesize -= len(block)
        file.close()
        self.filemessage.emit(filepath, filesender, GlobalData.currentUser)